import { Asset, BufferAsset } from "cc";
import { BundleMgr } from "../../mgr/BundleMgr";
import { ConfigMgr } from "../../mgr/ConfigMgr";
import { ILoading } from "./ILoading";


export class LoadingConfig implements ILoading {

    loadedProgress: number = 0;
    readonly totalProgress: number = 1;

    constructor(
        public bundleMgr: BundleMgr,
        public configMgr: ConfigMgr
    ) {

    }
    bLoading: boolean = false;
    bCompleted: boolean;
    load(): void {
        if (this.bLoading) {
            return;
        }
        this.bLoading = true;
        this.bundleMgr.config.load("config", BufferAsset,(err, data: BufferAsset) => {
            if (err) {
                console.error(" loading config dep load err ", err);
                return;
            }
            const zip = new JSZip(data.buffer());
            const files = zip.files;
            for (const key in files) {
                const keyFile = files[key];
                const name = keyFile.name;
                const text = keyFile.asText();
                try {
                    const data = JSON.parse(text);
                    const fileName = name.split(".")[0];
                    this.configMgr.data.set(fileName, data);
                } catch (e) {
                    console.error("load config ,error  ", e);
                }
            }
            this.loadedProgress++;

            this.bundleMgr.config.releaseAll();
        })
    }
    checkCompleted(): boolean {
        if (this.bCompleted) {
            return true;
        }
        const ret = this.loadedProgress >= this.totalProgress;        
        if (ret) {
            this.bCompleted = ret;
            this.target.onLoadingCompleted();
            return true;
        }
        return false;
    }
    getProgress(): number {
        return this.loadedProgress / this.totalProgress;
    }
    getProgressDesc(): string {
        return "正在加载配置..." + this.getProgress();
    }
    target: { onLoadingCompleted(): void };
}